<template>
  <b-page class="sop-edit">
    <a-form-model
      ref="form"
      :model="model"
      labelAlign="right"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-form-model-item label="规则名称" :required="true">
        <a-input
          class="ml-30"
          v-model="model.name"
          placeholder="请输入不超过16个字的规则名称"
          :maxLength="16"
          :suffix="model.name.length+'/16'"
          style="max-width: 370px"/>
      </a-form-model-item>
      <a-form-model-item label="选择群聊" :required="true">
        <div class="ml-30">
          <b-button
            type="default"
            ghost="default"
            btnContent="选择群聊"
            style="width: 88px"
            @click="showChat=true"/>
          <div class="d-aic mp-item-list-wrap">
            <div
              v-for="(item,index) in chatList"
              :key="index">
              <div class="d-aic mp-item-list" v-if="item.select">
                <img class="chat-img mr-10" src="../../../assets/group.png">
                <div class="mp-list-desc">
                  <div class="mp-list-name">{{ item.name?item.name:' ' }}<span
                    class="ml-10"
                    v-if="item.groupType===2"
                    style="color: #ff5f5f">外部</span>
                  </div>
                  <div class="mp-list-group">群主：{{ item.groupLeader?item.groupLeader:' ' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="推送规则设置" :required="true">
        <div class="ml-30">
          <div class="rule-list">
            <div
              class="rule d-jcc-aic"
              :class="index===activeIndex?'active':''"
              v-for="(item,index) in model.ruleList"
              :key="index"
              @click="changeRuleActive(index)"><span
                                                 :style="{color:index===activeIndex?'#de2f26':''}">规则{{ index+1 }}</span>
              <a-icon
                class="ml-10"
                v-if="index===activeIndex"
                type="close"
                @click.stop="delRule"/>
            </div>
            <div
              class="new-rule d-jcc-aic"
              @click="addRule">+新建规则</a-icon></div>
          </div>
          <div class="tab-content">
            <div>
              推送时间:
              <a-date-picker
                class="ml-30"
                v-model="currentEditRule.showPushTime"
                @change="changeTime"
                show-time
                style="max-width: 370px"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择时间"/>
            </div>
            <div>推送内容:
              <div class="edit-msg-box">
                <div class="edit-left">
                  <div
                    class="msg-li_active"
                    v-for="(msg,index) in currentEditRule.messageList"
                    :class="index===activeMsgIndex?'active':''"
                    @click="changeMsgActive(index)"
                    :key="index">消息 <span>{{ index+1 }}</span> <span> {{ msg.messageType==='TEXT'?'文字':msg.messageType==='IMAGE'?'图片':'图文' }}</span>
                  </div>
                  <div class="msg-li msg_add" @click="addMsg">新建</div>
                </div>
                <div class="edit_right">
                  <div class="msg-type">
                    <div>
                      <div class="msg-type-title"><span style="margin-right: 18px">消息类型：</span>
                        <div>
                          <a-radio-group
                            v-model="currentMsgEdit.messageType"
                            @change="typeChange">
                            <a-radio value="TEXT">
                              文字
                            </a-radio>
                            <a-radio value="IMAGE">
                              图片
                            </a-radio>
                            <a-radio value="TEXT-IMAGE">
                              图文
                            </a-radio>
                          </a-radio-group>
                        </div>
                      </div>
                      <div class="text-panel" v-if="currentMsgEdit.messageType==='TEXT'">
                        <div class="edit-msg-name">文字消息:</div>
                        <div>
                          <a-textarea
                            v-model="currentMsgEdit.showMsg.desc"
                            placeholder="请输入跟进内容"
                            :auto-size="{ minRows: 5, maxRows: 5 }"/>
                          <div class="textarea-count">{{ currentMsgEdit.showMsg.desc.length
                          }}/500
                          </div>
                          <div style="width: 100%; min-width: 450px;"></div>
                          <div
                            class="delete-box text-delete-box"
                            @click="delMsg">
                            <a-icon type="delete"/>
                            <span>删除此条消息</span>
                          </div>
                        </div>
                      </div>
                      <div class="text-panel" v-if="currentMsgEdit.messageType==='IMAGE'">
                        <div class="edit-msg-name">添加图片:</div>
                        <div>
                          <upload-lb
                            :posterUrl="currentMsgEdit.showMsg.img"
                            @input="uploadImg"/>
                          <div style="width: 100%; min-width: 450px;"></div>
                          <div
                            class="delete-box text-delete-box"
                            @click="delMsg">
                            <a-icon type="delete"/>
                            <span>删除此条消息</span>
                          </div>
                        </div>
                      </div>
                      <div class="text-panel" v-if="currentMsgEdit.messageType==='TEXT-IMAGE'">
                        <div>
                          <a-form-model
                            ref="msgForm"
                            :model="currentMsgEdit.showMsg"
                            labelAlign="right"
                            :label-col="msgLabelCol"
                            :wrapper-col="msgWrapperCol">
                            <a-form-model-item label="标题" :required="true">
                              <a-input
                                class="ml-30"
                                v-model="currentMsgEdit.showMsg.title"
                                placeholder="请输入不超过16个字的活动名称"
                                style="width: 300px"/>
                            </a-form-model-item>
                            <a-form-model-item label="描述" :required="true">
                              <a-textarea
                                class="ml-30"
                                v-model="currentMsgEdit.showMsg.desc"
                                style="width: 300px"
                                placeholder="请输入跟进内容"
                                :auto-size="{ minRows: 5, maxRows: 5 }"
                              />
                            </a-form-model-item>
                            <a-form-model-item label="跳转链接" :required="true">
                              <a-input
                                class="ml-30"
                                v-model="currentMsgEdit.showMsg.url"
                                placeholder="请输入不超过16个字的活动名称"
                                style="width: 300px"/>
                            </a-form-model-item>
                            <a-form-model-item label="上传封面图" :required="true">
                              <upload-lb
                                style="margin-left: 150px"
                                :posterUrl="currentMsgEdit.showMsg.img"
                                @input="uploadImg"/>
                            </a-form-model-item>
                          </a-form-model>
                          <div style="width: 100%; min-width: 450px;"></div>
                          <div
                            class="delete-box  text-delete-box"
                            @click="delMsg">
                            <a-icon type="delete"/>
                            <span>删除此条消息</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        </div>
      </a-form-model-item>
    </a-form-model>
    <a-modal v-model="showChat" title="选择群聊" :footer="null" width="640px">
      <div class="mp-list-wrap">
        <div v-if="!chatList.length">
          <a-empty/>
        </div>
        <div v-else>
          <div class="d-aic">
            <a-input
              v-model="chatName"
              placeholder="输入群名称"
              style="max-width: 370px"/>
            <a-button class="ml-10" type="primary" @click="getChatList()">搜索</a-button>
          </div>
          <div class="group-count">
            <div class="d-jcs-aic">
              <div>全部群聊（{{ chatList.length }}）：</div>
              <div>
                <a-checkbox
                  :indeterminate="indeterminate"
                  :checked="checkAll"
                  @change="onCheckAllChange">
                  全选
                </a-checkbox>
              </div>
            </div>
            <div>
              <a-checkbox-group v-model="selectChatIdList" @change="onCheckChange" style="width: 100%">
                <a-checkbox
                  class="chat-item d-jcs-aic"
                  :value="item.groupChatId"
                  v-for="(item,index) in chatList"
                  :key="index">
                  <div class="d-aic">
                    <img class="chat-img" src="../../../../assets/chatGroup.jpg">
                    <div>
                      <div>{{ item.name }}</div>
                      <div class="chat-group-name">群主：{{ item.groupLeader }}</div>
                    </div>
                  </div>
                </a-checkbox>
              </a-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div class="d-aic" style="justify-content: flex-end;">
        <b-button key="submit" type="primary" @click="saveGroup" btnContent="确定"/>
      </div>
    </a-modal>
    <div class="operator-btn-list">
      <div class="operator-btn-content">
        <b-button
          type="default"
          ghost="default"
          btnContent="取消"
          style="margin: 0 8px"
          @click="back"/>
        <b-button
          type="primary"
          btnContent="保存"
          @click="saveChat"/>
      </div>
    </div>
  </b-page>
</template>

<script>
    import BButton from '../../../components/b-button'
    import API from '../../../../api/sop'
    import GROUP_API from '../../../../api/group'
    import UploadLb from '../../../components/upload'
    import moment from 'moment'

    export default {
        name: 'SopEdit',
        components: { UploadLb, BButton },
        props: {
            customerId: {
                type: [Number, String],
                default: null
            }
        },
        data () {
            return {
                labelCol: { lg: { span: 4 }, sm: { span: 4 } },
                wrapperCol: {
                    xs: { span: 20 }
                },
                msgLabelCol: { span: 6 },
                msgWrapperCol: { span: 18 },
                showChat: false,
                indeterminate: false,
                // 是否全选
                checkAll: false,
                selectChatIdList: [],
                chatList: [],
                chatIdList: [],
                // 搜索群聊
                chatName: '',
                // 当前激活的规则index
                activeIndex: 0,
                // 当前激活的消息index
                activeMsgIndex: 0,
                model: {
                    name: '',
                    targetList: [],
                    groupChatList: [],
                    groupChatIdList: [],
                    ruleList: [{
                        pushTime: null,
                        showPushTime: '',
                        messageList: [
                            {
                                messageType: 'TEXT',
                                showMsg: { title: '', desc: '', url: '', img: '' }
                            }
                        ]
                    }]
                }
            }
        },
        computed: {
            qwUserId () {
                return this.$store.state.user.info.qwUserId
            },
            currentEditRule () {
                return this.model.ruleList[this.activeIndex]
            },
            currentMsgEdit () {
                return this.currentEditRule.messageList[this.activeMsgIndex]
            }
        },
        mounted () {
            this.open()
        },
        methods: {
            open () {
                if (this.customerId) {
                    this.getModel()
                } else {
                    this.initModel()
                    this.getChatList()
                    this.loading = true
                }
            },
            getModel () {
                API.getSop({ id: this.customerId, qwUserId: this.qwUserId }).then(res => {
                    try {
                        // 全局解析消息内容
                        res.ruleList.forEach(msgList => {
                            this.$set(msgList, 'showPushTime', msgList.pushTime ? moment(this.$Utils.getTimeFormat(msgList.pushTime), 'YYYY-MM-DD HH:mm:ss') : '')
                            msgList.messageList.forEach(contentList => {
                                contentList.showMsg = JSON.parse(contentList.content)
                            })
                        })
                    } catch (e) {
                        console.log(e)
                        res.ruleList = {
                            pushTime: null,
                            showPushTime: '',
                            messageList: [
                                {
                                    messageType: 'TEXT',
                                    showMsg: { title: '', desc: '', url: '', img: '' }
                                }
                            ]
                        }
                        this.$message.error('Sop信息出错')
                    }
                    this.model = Object.assign({}, res)
                    // 初始化被选中的群聊
                    this.initSelectGroup()
                })
            },
            initTime () {
                const time = this.$Utils.getTimeFormat(this.currentEditRule.pushTime)
                this.$set(this.model.ruleList[this.activeIndex], 'showPushTime', this.currentEditRule.pushTime ? moment(time, 'YYYY-MM-DD HH:mm:ss') : '')
            },
            initModel () {
                this.model.qwUserId = this.qwUserId
            },
            initSelectGroup () {
                // 先获得所有群聊
                this.getChatList()
            },
            /**
             * 修改上传图片
             * @param data
             */
            uploadImg (data) {
                this.model.ruleList[this.activeIndex].messageList[this.activeMsgIndex].content.img = data
            },
            /**
             * 切换之前记得把数据先赋值给model,然后切换新值
             */
            changeRuleActive (index) {
                this.activeIndex = index
                this.initTime()
            },
            changeMsgActive (index) {
                this.activeMsgIndex = index
            },
            /**
             * 全选修改选中值，并把选中中间状态设为false
             * @param e
             */
            onCheckAllChange (e) {
                Object.assign(this, {
                    selectChatIdList: e.target.checked ? this.chatIdList : [],
                    indeterminate: false,
                    checkAll: e.target.checked
                })
                // 操作展示选中的群聊
                let select = false
                if (e.target.checked) {
                    select = true
                }
                this.chatList.forEach(item => {
                    item.select = select
                })
            },
            /**
             * 切换群聊选中状态，根据选中值数量判断是否切换选中中间状态
             * @param selectChatIdList
             */
            onCheckChange (selectChatIdList) {
                this.indeterminate = !!selectChatIdList.length && selectChatIdList.length < this.chatList.length
                this.checkAll = selectChatIdList.length === this.chatList.length
                selectChatIdList.forEach(item => {
                    this.chatList.forEach(chat => {
                        if (chat.groupChatId === item) {
                            chat.select = true
                        }
                    })
                })
            },
            /**
             * 增加规则，修改当前激活的panel，并且把当前激活的pannel数据赋值给元数据
             */
            addRule () {
                if (this.model.ruleList.length > 4) {
                    this.$message.error('最多添加五条规则')
                    return
                }
                this.model.ruleList.push({
                    pushTime: null,
                    showPushTime: '',
                    messageList: [
                        {
                            messageType: 'TEXT',
                            showMsg: { title: '', desc: '', url: '', img: '' }
                        }
                    ]
                })
                this.activeIndex = this.model.ruleList.length - 1
                console.log(this.model)
            },
            /**
             *添加消息最多十条，判断有多少规则，每个规则有多少消息，累加
             */
            addMsg () {
                const ruleLength = this.model.ruleList.length
                let msgLength = 0
                this.model.ruleList.forEach(item => {
                    msgLength += item.messageList.length
                })
                if (msgLength + ruleLength > 10) {
                    this.$message.error('最多添加十条消息')
                    return
                }
                this.model.ruleList[this.activeIndex].messageList.push({
                    messageType: 'TEXT',
                    showMsg: { title: '', desc: '', url: '', img: '' }
                })
                this.activeMsgIndex = this.model.ruleList[this.activeIndex].messageList.length - 1
            },
            /**
             * 删除规则，修改当前激活的panel
             */
            delRule () {
                const self = this
                if (self.model.ruleList.length === 1) {
                    this.$message.warning('规则至少保留一条')
                }
                this.$warning({
                    title: `确定要删除吗?`,
                    okText: '确认',
                    okType: 'primary',
                    maskClosable: true,
                    onOk () {
                        self.model.ruleList.splice(self.activeIndex, 1)
                        self.activeIndex = self.model.ruleList.length - 1
                    }
                })
            },
            typeChange (e) {
                // 修改当前编辑的和当前规则中的
                this.model.ruleList[this.activeIndex].messageList[this.activeMsgIndex].messageType = e.target.value
            },
            back () {
                this.$emit('onGoBack')
            },
            saveGroup () {
                this.showChat = false
            },
            saveChat () {
                // 用当前编辑的ruleList替换model中的数据
                this.selectChatIdList.forEach(item => {
                    this.model.targetList.push({ groupChatId: item })
                })
                this.model.ruleList.forEach(rule => {
                    rule.messageList.forEach(msg => {
                        this.$set(msg, 'content', JSON.stringify(msg.showMsg))
                    })
                })
                API.saveSop(this.model).then(() => {
                    this.$message.success('保存成功')
                    this.back()
                })
            },
            changeTime (data, dataString) {
                this.model.ruleList[this.activeIndex].pushTime = new Date(dataString.replace(/-/g, '/')).getTime()
                this.model.ruleList[this.activeIndex].showPushTime = data
            },
            delMsg () {
                const self = this
                if (self.model.ruleList[self.activeIndex].messageList.length === 1) {
                    this.$message.warning('消息至少保留一条')
                }
                this.$warning({
                    title: `确定要删除吗?`,
                    okText: '确认',
                    okType: 'primary',
                    maskClosable: true,
                    onOk () {
                        self.model.ruleList[self.activeIndex].messageList.splice(self.activeMsgIndex, 1)
                        self.activeMsgIndex = self.model.ruleList[self.activeIndex].messageList.length - 1
                    }
                })
            },
            getChatList () {
                GROUP_API.pageGroup({
                    qwUserId: this.qwUserId,
                    keyword: this.chatName,
                    current: 1,
                    pageSize: 1000
                }).then(res => {
                    let records = res.records
                    records = records.map(item => {
                        return {
                            ...item,
                            select: false
                        }
                    })
                    records.forEach(item => {
                        this.chatIdList.push(item.groupChatId)
                    })
                    if (this.customerId) {
                        this.model.targetList.forEach(item => {
                            records.forEach(mp => {
                                if (mp.groupChatId === item.groupChatId) {
                                    this.selectChatIdList.push(mp.groupChatId)
                                    this.indeterminate = true
                                    mp.select = true
                                    item.select = true
                                }
                            })
                        })
                    }
                    this.chatList = records
                }).catch()
            }
        }
    }
</script>

<style scoped lang="less">
    .chat-img {
        width: 40px;
        height: 40px;
        border-radius: 3px;
        margin-right: 11px;
    }

    .chat-group-name {
        font-size: 12px;
        color: #999;
        opacity: .85;
        width: 140px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .group-count {
        display: block;
        font-size: 13px;
        color: #666;
        margin-top: 8px;
        margin-bottom: 6px;
        text-align: left;

        .chat-img {
            width: 40px;
            height: 40px;
            border-radius: 3px;
            margin-right: 11px;
        }

        .chat-group-name {
            font-size: 12px;
            color: #999;
            opacity: .85;
            width: 140px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item {
            margin-left: 0 !important;
            padding: 5px 10px 5px 0;
            flex-direction: row-reverse;
            border-bottom: 1px dashed #e9e9e9;
        }
    }

    .sop-edit {
        .mp-item-list-wrap {
            width: 850px;
            flex-wrap: wrap;
        }

        .mp-item-list {
            margin: 10px;
            width: 200px;
            height: 50px;

            .mp-list-desc {
                height: 40px;
            }
        }

        .mp-list-name {
            padding-right: 10px;
            width: 180px;
            height: 20px;
            line-height: 20px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .mp-list-group {
            width: 180px;
            height: 20px;
            line-height: 20px;
            white-space: nowrap;
            color: #9f9f9f;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .tab-content {
            width: 775px;
            padding: 24px 32px;
            margin-top: -1px;
            background: #fbfbfb;
            border: 1px solid #f2f2f2;
        }

        .edit-msg-box {
            display: flex;
            padding: 0 13px 0 0;

            .edit-left {
                text-align: center;
                width: 105px;
            }

            .msg-li_active {
                width: 100%;
                height: 44px;
                line-height: 44px;
                margin-bottom: 10px;
                border-radius: 2px 0 0 2px;
                color: #333;
                cursor: pointer;
                position: relative;
                &.active{
                    background: #fff;
                    box-shadow: 0 0 4px 0 rgba(0, 0, 0, .08);
                }
            }
            .msg_add {
                color: #222;
                background: unset;
                border: 1px dashed #ddd;
                border-right: none;
            }

            .msg-li_active {
                width: 100%;
                height: 44px;
                line-height: 44px;
                margin-bottom: 10px;
                border-radius: 2px 0 0 2px;
                color: #333;
                cursor: pointer;
                position: relative;
            }

            .edit_right {
                padding: 24px 32px;
                width: 90%;
                background: #fff;
                box-shadow: 0 0 4px 0 rgba(0, 0, 0, .08);
            }

            .msg-type {
                display: flex;
                margin-bottom: 32px;
            }

            .msg-type-title {
                display: flex;
                margin-bottom: 24px;
            }

            .edit-msg-name {
                width: 65px;
                height: 20px;
                line-height: 20px;
                margin-right: 18px;
                white-space: nowrap;
            }

            .text-panel {
                display: flex;
                flex-direction: row;
            }

            .textarea-count {
                font-size: 14px;
                color: #bbb;
                line-height: 26px;
                margin-bottom: 0 !important;
                float: right;
            }

            .delete-box {
                margin-top: 20px;
                display: flex;
                align-items: center;
                color: #666;
                cursor: pointer;
                width: 120px;
                user-select: none;
            }
        }

        .rule-list {
            display: flex;

            .rule {
                width: 103px;
                height: 43px;
                border: 1px solid #ececec;
                cursor: pointer;
                user-select: none;
                margin-right: 5px;

                &.active {
                    background: #fbfbfb;
                    position: relative;
                    cursor: default;
                }
            }
        }

        .new-rule {
            width: 103px;
            height: 43px;
            border: 1px solid #ececec;
            cursor: pointer;
            user-select: none;
            margin-right: 5px;
        }

        .operator-btn-list {
            position: fixed;
            left: 256px;
            width: 100%;
            bottom: 0;
            background: white;
            z-index: 100;

            .operator-btn-content {
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: center;
                align-items: center;
                box-shadow: 0 -1px 0px 0px #eee;
            }
        }
    }
</style>
